package com.ysmygx.service.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ysmygx.entity.ResponseBody;
import com.ysmygx.service.EnvelopeService;
import com.ysmygx.utils.BusinessException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import com.ysmygx.utils.ThreadLocalUtil;

import javax.xml.xpath.XPathConstants;

@Log4j2
@Service
public class EnvelopeServiceImpl implements EnvelopeService {



    @Value("${pay.envelope-url}")
    private String url;

    private final String contentTypeEnc = "INFOSEC_ENC_ENVELOPE/1.0";

    private final String contentTypeDec = "INFOSEC_DEC_ENVELOPE/1.0";

    @Value("${pay.customer-sn}")
    private String customerSn;

    @Value("${pay.bank-sn}")
    private String bankSn;

    /**
     * 制作加密信封
     * @param requestBody
     * @return
     */
    public String enc(String requestBody){
        log.info("调用链路序号:{},请求参数:{}", ThreadLocalUtil.get(), requestBody);
        HttpResponse response = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, contentTypeEnc)
                .header("CertSN", bankSn)
                .header("Accept-Encoding", "*")
                .body(requestBody)
                .execute();
        String sign = null;
        if (response.isOk()){
            String html = response.body();
            Document document = XmlUtil.readXML(html);
            sign = XmlUtil.getByXPath("//html/body/data", document, XPathConstants.STRING).toString();
        }

//        log.info(sign);
        return sign;
    }


    public Object dec(String encData, Class dataClass) throws InstantiationException, IllegalAccessException {
        HttpResponse response = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, contentTypeDec)
                .header("CertSN", customerSn)
                .header("Accept-Encoding", "*")
                .body(encData)
                .execute();



        Object data = dataClass.newInstance();
        if (response.isOk()){
            String html = response.body();
            Document document = XmlUtil.readXML(html);
            String dataJson = XmlUtil.getByXPath("//html/body/sic", document, XPathConstants.STRING).toString();
            log.info("调用链路序号:{},返回参数：{}", ThreadLocalUtil.get(),
                    dataJson.length()<200?dataJson:dataJson.substring(0, 200));


            ResponseBody responseBody = JSON.parseObject(dataJson, ResponseBody.class);
            if ( ! responseBody.getEc().equals("0")){
                log.error("调用链路序号:{},返回状态不是0：{}",ThreadLocalUtil.get(), JSONUtil.toJsonStr(responseBody));
                throw new BusinessException(responseBody.getEm());
            }
//            log.info(responseBody);
            data  = JSON.parseObject(responseBody.getData().toString(), dataClass);
        }else{
            log.error("调用链路序号:{},请求银行接口响应异常：{}",ThreadLocalUtil.get(), JSONUtil.toJsonStr(response));
            throw new BusinessException(JSONUtil.toJsonStr(response));
        }

        return data;
    }
}
